package com.liyuxiang.graph.node;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.alibaba.cloud.ai.graph.action.NodeAction;
import com.liyuxiang.graph.service.SymptomAnalysisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SymptomDetailNode implements NodeAction {
    
    private static final Logger logger = LoggerFactory.getLogger(SymptomDetailNode.class);
    private final SymptomAnalysisService symptomAnalysisService;
    
    public SymptomDetailNode(SymptomAnalysisService symptomAnalysisService) {
        this.symptomAnalysisService = symptomAnalysisService;
    }
    
    @Override
    public Map<String, Object> apply(OverAllState state) throws Exception {
        String query = state.value("query", "");
        String userId = state.value("userId", "unknown");
        List<String> history = state.value("conversationHistory", List.of());
        Map<String, Object> symptoms = state.value("symptoms", new HashMap<>());
        Integer questionCount = state.value("questionCount", 0);
        
        logger.info("开始AI症状详情收集 - 用户ID: {}, 问题轮次: {}, 当前症状数: {}", 
                userId, questionCount + 1, symptoms.size());
        
        try {
            // 使用AI症状分析服务
            SymptomAnalysisService.SymptomAnalysisResult analysisResult = 
                    symptomAnalysisService.analyzeSymptom(query, history, symptoms, questionCount, userId);
            
            // 合并提取的症状信息
            Map<String, Object> updatedSymptoms = new HashMap<>(symptoms);
            updatedSymptoms.putAll(analysisResult.getExtractedSymptoms());
            
            // 构建完整的对话历史（不重复添加用户输入，因为Controller已经添加了）
            List<String> updatedHistory = new java.util.ArrayList<>(history);
            
            // 检查是否已经包含当前用户输入
            String currentUserInput = "用户: " + query;
            if (!updatedHistory.contains(currentUserInput)) {
                updatedHistory.add(currentUserInput);
                logger.info("添加用户输入到对话历史: {}", currentUserInput);
            } else {
                logger.info("用户输入已存在于对话历史中，跳过重复添加");
            }
            
            String response = analysisResult.getNextQuestion();
            if (response != null && !response.trim().isEmpty()) {
                String assistantResponse = "助手: " + response;
                updatedHistory.add(assistantResponse);
                logger.info("添加助手回复到对话历史: {}", assistantResponse);
            }
            
            // 记录详细的分析信息
            logger.info("AI症状分析结果 - 用户ID: {}, 继续询问: {}, 完整度: {}, 紧急度: {}", 
                    userId, analysisResult.shouldContinue(), analysisResult.getCompleteness(), analysisResult.getUrgency());
            logger.info("分析理由: {}", analysisResult.getReason());
            logger.info("提取症状: {}", analysisResult.getExtractedSymptoms().keySet());
            
            Map<String, Object> result = new HashMap<>();
            result.put("response", response);
            result.put("symptoms", updatedSymptoms);
            result.put("conversationHistory", updatedHistory);
            result.put("questionCount", questionCount + 1);
            result.put("shouldContinue", analysisResult.shouldContinue());
            result.put("confidence", analysisResult.getConfidence());
            result.put("completeness", analysisResult.getCompleteness());
            result.put("urgency", analysisResult.getUrgency());
            result.put("suggestedAction", analysisResult.getSuggestedAction());
            result.put("reason", analysisResult.getReason());
            result.put("fullAiAnalysis", analysisResult.isFullAiAnalysis());
            
            logger.info("AI症状详情收集完成 - 用户ID: {}, 最终决策: {}, AI分析: {}", 
                    userId, analysisResult.getSuggestedAction(), analysisResult.isFullAiAnalysis());
            
            return result;
            
        } catch (Exception e) {
            logger.error("AI症状详情收集失败 - 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            
            // 构建对话历史（备用逻辑）
            List<String> updatedHistory = new java.util.ArrayList<>(history);
            String currentUserInput = "用户: " + query;
            if (!updatedHistory.contains(currentUserInput)) {
                updatedHistory.add(currentUserInput);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("response", "请详细描述一下您的症状，比如具体的不适感受和持续时间？");
            result.put("symptoms", symptoms);
            result.put("conversationHistory", updatedHistory);
            result.put("questionCount", questionCount + 1);
            result.put("shouldContinue", questionCount < 3);
            result.put("error", e.getMessage());
            result.put("fallback", true);
            
            logger.warn("使用默认症状收集策略");
            return result;
        }
    }
}